package com.dayaokeji.rhythmschoolstudent.client.common.vote;

import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.LinearLayout;

import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.view.VoteResultItemView;
import com.dayaokeji.server_api.domain.VoteItem;

import org.jetbrains.annotations.Contract;

import java.util.List;

import butterknife.BindView;

/**
 * 投票结果
 */
public class VoteResultActivity extends BaseActivity {

    public static final String EXTRA_VOTE_TITLE = "vote_title";
    public static final String EXTRA_VOTE_LIST = "vote_list";

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.ll_vote_result_content)
    LinearLayout llVoteResultContent;

    private List<VoteItem> voteItemList;
    private String voteTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vote_result);
        setSupportActionBar(toolbar);

        voteItemList = (List<VoteItem>) getIntent().getSerializableExtra(EXTRA_VOTE_LIST);
        voteTitle = getIntent().getStringExtra(EXTRA_VOTE_TITLE);

        if (voteItemList == null) {
            ToastUtils.warning(R.string.data_incorrect);
            return;
        }

        init();
    }

    private void init() {
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(voteTitle);
        }
        initData();
    }

    private void initData() {
        int totalCount = 0;
        for (VoteItem voteItem : voteItemList) {
            totalCount += voteItem.getCount();
        }

        if (voteItemList != null && voteItemList.size() > 0) {
            for (VoteItem voteItem : voteItemList) {
                VoteResultItemView voteResultItemView = new VoteResultItemView(VoteResultActivity.this, calPercent(totalCount, voteItem.getCount()), voteItem.getContent(),voteItem.getCount());
                llVoteResultContent.addView(voteResultItemView);
            }
        }
    }

    @Contract(pure = true)
    private float calPercent(float totalCount , float count) {
        if (count == 0 || totalCount == 0){
            return 0;
        }
        return count / totalCount;
    }
}
